home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 12 / Cream of the Crop 12 (Part II) / Cream of the Crop 12 (Part II).iso / OS2 / GNUSED.ZIP / doc / rx.info < prev    next >
Encoding:
GNU Info File  |  1995-12-31  |  36.4 KB  |  947 lines

  1. This is Info file rx.info, produced by Makeinfo-1.63 from the input
  2. file rx.texi.
  3.  
  4. 
  5. File: rx.info,  Node: Top,  Next: Posix Entry Points,  Prev: (dir),  Up: (dir)
  6.  
  7. Rx
  8. **
  9.  
  10.    This document describes Rx.
  11.  
  12.    This document applies to version "Rx-diSpencer" of the library named
  13. librx.a
  14.  
  15. * Menu:
  16.  
  17. * Posix Entry Points::
  18. * Performance Considerations::  Special considerations when using Rx.
  19. * Semantic Tests::              A test-suite for Posix matcher semantics.
  20. * General Functions::           Rx's native entry points.
  21. * Rx Theory::                   A quick tour of the implementation.
  22. * Improvements to Make::        The Rx TODO list.
  23.  
  24. 
  25. File: rx.info,  Node: Posix Entry Points,  Next: Performance Considerations,  Prev: Top,  Up: Top
  26.  
  27. Regular Expression Matching
  28. ===========================
  29.  
  30.    This section is excerpted from *The GNU C Library* reference manual
  31. by Sandra Loosemore with Richard M. Stallman, Roland McGrath, and Andrew
  32. Oram.
  33.  
  34.    The GNU C library supports the standard POSIX.2 interface.  Programs
  35. using this interface should include the header file `rx.h'.
  36.  
  37. * Menu:
  38.  
  39. * POSIX Regexp Compilation::    Using `regcomp' to prepare to match.
  40. * Flags for POSIX Regexps::     Syntax variations for `regcomp'.
  41. * Matching POSIX Regexps::      Using `regexec' to match the compiled
  42.                    pattern that you get from `regcomp'.
  43. * Regexp Subexpressions::       Finding which parts of the string were matched.
  44. * Subexpression Complications:: Find points of which parts were matched.
  45. * Regexp Cleanup::        Freeing storage; reporting errors.
  46.  
  47. 
  48. File: rx.info,  Node: POSIX Regexp Compilation,  Next: Flags for POSIX Regexps,  Up: Posix Entry Points
  49.  
  50. POSIX Regular Expression Compilation
  51. ------------------------------------
  52.  
  53.    Before you can actually match a regular expression, you must
  54. "compile" it.  This is not true compilation--it produces a special data
  55. structure, not machine instructions.  But it is like ordinary
  56. compilation in that its purpose is to enable you to "execute" the
  57. pattern fast.  (*Note Matching POSIX Regexps::, for how to use the
  58. compiled regular expression for matching.)
  59.  
  60.    There is a special data type for compiled regular expressions:
  61.  
  62.  - Data Type: regex_t
  63.      This type of object holds a compiled regular expression.  It is
  64.      actually a structure.  It has just one field that your programs
  65.      should look at:
  66.  
  67.     `re_nsub'
  68.           This field holds the number of parenthetical subexpressions
  69.           in the regular expression that was compiled.
  70.  
  71.      There are several other fields, but we don't describe them here,
  72.      because only the functions in the library should use them.
  73.  
  74.    After you create a `regex_t' object, you can compile a regular
  75. expression into it by calling `regcomp'.
  76.  
  77.  - Function: int regcomp (regex_t *COMPILED, const char *PATTERN, int
  78.           CFLAGS)
  79.      The function `regcomp' "compiles" a regular expression into a data
  80.      structure that you can use with `regexec' to match against a
  81.      string.  The compiled regular expression format is designed for
  82.      efficient matching.  `regcomp' stores it into `*COMPILED'.
  83.  
  84.      It's up to you to allocate an object of type `regex_t' and pass its
  85.      address to `regcomp'.
  86.  
  87.      The argument CFLAGS lets you specify various options that control
  88.      the syntax and semantics of regular expressions.  *Note Flags for
  89.      POSIX Regexps::.
  90.  
  91.      If you use the flag `REG_NOSUB', then `regcomp' omits from the
  92.      compiled regular expression the information necessary to record
  93.      how subexpressions actually match.  In this case, you might as well
  94.      pass `0' for the MATCHPTR and NMATCH arguments when you call
  95.      `regexec'.
  96.  
  97.      If you don't use `REG_NOSUB', then the compiled regular expression
  98.      does have the capacity to record how subexpressions match.  Also,
  99.      `regcomp' tells you how many subexpressions PATTERN has, by
  100.      storing the number in `COMPILED->re_nsub'.  You can use that value
  101.      to decide how long an array to allocate to hold information about
  102.      subexpression matches.
  103.  
  104.      `regcomp' returns `0' if it succeeds in compiling the regular
  105.      expression; otherwise, it returns a nonzero error code (see the
  106.      table below).  You can use `regerror' to produce an error message
  107.      string describing the reason for a nonzero value; see *Note Regexp
  108.      Cleanup::.
  109.  
  110.  
  111.    Here are the possible nonzero values that `regcomp' can return:
  112.  
  113. `REG_BADBR'
  114.      There was an invalid `\{...\}' construct in the regular
  115.      expression.  A valid `\{...\}' construct must contain either a
  116.      single number, or two numbers in increasing order separated by a
  117.      comma.
  118.  
  119. `REG_BADPAT'
  120.      There was a syntax error in the regular expression.
  121.  
  122. `REG_BADRPT'
  123.      A repetition operator such as `?' or `*' appeared in a bad
  124.      position (with no preceding subexpression to act on).
  125.  
  126. `REG_ECOLLATE'
  127.      The regular expression referred to an invalid collating element
  128.      (one not defined in the current locale for string collation).
  129.  
  130. `REG_ECTYPE'
  131.      The regular expression referred to an invalid character class name.
  132.  
  133. `REG_EESCAPE'
  134.      The regular expression ended with `\'.
  135.  
  136. `REG_ESUBREG'
  137.      There was an invalid number in the `\DIGIT' construct.
  138.  
  139. `REG_EBRACK'
  140.      There were unbalanced square brackets in the regular expression.
  141.  
  142. `REG_EPAREN'
  143.      An extended regular expression had unbalanced parentheses, or a
  144.      basic regular expression had unbalanced `\(' and `\)'.
  145.  
  146. `REG_EBRACE'
  147.      The regular expression had unbalanced `\{' and `\}'.
  148.  
  149. `REG_ERANGE'
  150.      One of the endpoints in a range expression was invalid.
  151.  
  152. `REG_ESPACE'
  153.      `regcomp' ran out of memory.
  154.  
  155. 
  156. File: rx.info,  Node: Flags for POSIX Regexps,  Next: Matching POSIX Regexps,  Prev: POSIX Regexp Compilation,  Up: Posix Entry Points
  157.  
  158. Flags for POSIX Regular Expressions
  159. -----------------------------------
  160.  
  161.    These are the bit flags that you can use in the CFLAGS operand when
  162. compiling a regular expression with `regcomp'.
  163.  
  164. `REG_EXTENDED'
  165.      Treat the pattern as an extended regular expression, rather than
  166.      as a basic regular expression.
  167.  
  168. `REG_ICASE'
  169.      Ignore case when matching letters.
  170.  
  171. `REG_NOSUB'
  172.      Don't bother storing the contents of the MATCHES-PTR array.
  173.  
  174. `REG_NEWLINE'
  175.      Treat a newline in STRING as dividing STRING into multiple lines,
  176.      so that `$' can match before the newline and `^' can match after.
  177.      Also, don't permit `.' to match a newline, and don't permit
  178.      `[^...]' to match a newline.
  179.  
  180.      Otherwise, newline acts like any other ordinary character.
  181.  
  182. 
  183. File: rx.info,  Node: Matching POSIX Regexps,  Next: Regexp Subexpressions,  Prev: Flags for POSIX Regexps,  Up: Posix Entry Points
  184.  
  185. Matching a Compiled POSIX Regular Expression
  186. --------------------------------------------
  187.  
  188.    Once you have compiled a regular expression, as described in *Note
  189. POSIX Regexp Compilation::, you can match it against strings using
  190. `regexec'.  A match anywhere inside the string counts as success,
  191. unless the regular expression contains anchor characters (`^' or `$').
  192.  
  193.  - Function: int regexec (regex_t *COMPILED, char *STRING, size_t
  194.           NMATCH, regmatch_t MATCHPTR [], int EFLAGS)
  195.      This function tries to match the compiled regular expression
  196.      `*COMPILED' against STRING.
  197.  
  198.      `regexec' returns `0' if the regular expression matches;
  199.      otherwise, it returns a nonzero value.  See the table below for
  200.      what nonzero values mean.  You can use `regerror' to produce an
  201.      error message string describing the reason for a nonzero value;
  202.      see *Note Regexp Cleanup::.
  203.  
  204.      The argument EFLAGS is a word of bit flags that enable various
  205.      options.
  206.  
  207.      If you want to get information about what part of STRING actually
  208.      matched the regular expression or its subexpressions, use the
  209.      arguments MATCHPTR and NMATCH.  Otherwise, pass `0' for NMATCH,
  210.      and `NULL' for MATCHPTR.  *Note Regexp Subexpressions::.
  211.  
  212.    You must match the regular expression with the same set of current
  213. locales that were in effect when you compiled the regular expression.
  214.  
  215.    The function `regexec' accepts the following flags in the EFLAGS
  216. argument:
  217.  
  218. `REG_NOTBOL'
  219.      Do not regard the beginning of the specified string as the
  220.      beginning of a line; more generally, don't make any assumptions
  221.      about what text might precede it.
  222.  
  223. `REG_NOTEOL'
  224.      Do not regard the end of the specified string as the end of a
  225.      line; more generally, don't make any assumptions about what text
  226.      might follow it.
  227.  
  228.    Here are the possible nonzero values that `regexec' can return:
  229.  
  230. `REG_NOMATCH'
  231.      The pattern didn't match the string.  This isn't really an error.
  232.  
  233. `REG_ESPACE'
  234.      `regexec' ran out of memory.
  235.  
  236. 
  237. File: rx.info,  Node: Regexp Subexpressions,  Next: Subexpression Complications,  Prev: Matching POSIX Regexps,  Up: Posix Entry Points
  238.  
  239. Match Results with Subexpressions
  240. ---------------------------------
  241.  
  242.    When `regexec' matches parenthetical subexpressions of PATTERN, it
  243. records which parts of STRING they match.  It returns that information
  244. by storing the offsets into an array whose elements are structures of
  245. type `regmatch_t'.  The first element of the array (index `0') records
  246. the part of the string that matched the entire regular expression.
  247. Each other element of the array records the beginning and end of the
  248. part that matched a single parenthetical subexpression.
  249.  
  250.  - Data Type: regmatch_t
  251.      This is the data type of the MATCHARRAY array that you pass to
  252.      `regexec'.  It containes two structure fields, as follows:
  253.  
  254.     `rm_so'
  255.           The offset in STRING of the beginning of a substring.  Add
  256.           this value to STRING to get the address of that part.
  257.  
  258.     `rm_eo'
  259.           The offset in STRING of the end of the substring.
  260.  
  261.  - Data Type: regoff_t
  262.      `regoff_t' is an alias for another signed integer type.  The
  263.      fields of `regmatch_t' have type `regoff_t'.
  264.  
  265.    The `regmatch_t' elements correspond to subexpressions positionally;
  266. the first element (index `1') records where the first subexpression
  267. matched, the second element records the second subexpression, and so
  268. on.  The order of the subexpressions is the order in which they begin.
  269.  
  270.    When you call `regexec', you specify how long the MATCHPTR array is,
  271. with the NMATCH argument.  This tells `regexec' how many elements to
  272. store.  If the actual regular expression has more than NMATCH
  273. subexpressions, then you won't get offset information about the rest of
  274. them.  But this doesn't alter whether the pattern matches a particular
  275. string or not.
  276.  
  277.    If you don't want `regexec' to return any information about where
  278. the subexpressions matched, you can either supply `0' for NMATCH, or
  279. use the flag `REG_NOSUB' when you compile the pattern with `regcomp'.
  280.  
  281. 
  282. File: rx.info,  Node: Subexpression Complications,  Next: Regexp Cleanup,  Prev: Regexp Subexpressions,  Up: Posix Entry Points
  283.  
  284. Complications in Subexpression Matching
  285. ---------------------------------------
  286.  
  287.    Sometimes a subexpression matches a substring of no characters.  This
  288. happens when `f\(o*\)' matches the string `fum'.  (It really matches
  289. just the `f'.)  In this case, both of the offsets identify the point in
  290. the string where the null substring was found.  In this example, the
  291. offsets are both `1'.
  292.  
  293.    Sometimes the entire regular expression can match without using some
  294. of its subexpressions at all--for example, when `ba\(na\)*' matches the
  295. string `ba', the parenthetical subexpression is not used.  When this
  296. happens, `regexec' stores `-1' in both fields of the element for that
  297. subexpression.
  298.  
  299.    Sometimes matching the entire regular expression can match a
  300. particular subexpression more than once--for example, when `ba\(na\)*'
  301. matches the string `bananana', the parenthetical subexpression matches
  302. three times.  When this happens, `regexec' usually stores the offsets
  303. of the last part of the string that matched the subexpression.  In the
  304. case of `bananana', these offsets are `6' and `8'.
  305.  
  306.    But the last match is not always the one that is chosen.  It's more
  307. accurate to say that the last *opportunity* to match is the one that
  308. takes precedence.  What this means is that when one subexpression
  309. appears within another, then the results reported for the inner
  310. subexpression reflect whatever happened on the last match of the outer
  311. subexpression.  For an example, consider `\(ba\(na\)*s \)*' matching
  312. the string `bananas bas '.  The last time the inner expression actually
  313. matches is near the end of the first word.  But it is *considered*
  314. again in the second word, and fails to match there.  `regexec' reports
  315. nonuse of the "na" subexpression.
  316.  
  317.    Another place where this rule applies is when the regular expression
  318. `\(ba\(na\)*s \|nefer\(ti\)* \)*' matches `bananas nefertiti'.  The
  319. "na" subexpression does match in the first word, but it doesn't match
  320. in the second word because the other alternative is used there.  Once
  321. again, the second repetition of the outer subexpression overrides the
  322. first, and within that second repetition, the "na" subexpression is not
  323. used.  So `regexec' reports nonuse of the "na" subexpression.
  324.  
  325. 
  326. File: rx.info,  Node: Regexp Cleanup,  Prev: Subexpression Complications,  Up: Posix Entry Points
  327.  
  328. POSIX Regexp Matching Cleanup
  329. -----------------------------
  330.  
  331.    When you are finished using a compiled regular expression, you can
  332. free the storage it uses by calling `regfree'.
  333.  
  334.  - Function: void regfree (regex_t *COMPILED)
  335.      Calling `regfree' frees all the storage that `*COMPILED' points
  336.      to.  This includes various internal fields of the `regex_t'
  337.      structure that aren't documented in this manual.
  338.  
  339.      `regfree' does not free the object `*COMPILED' itself.
  340.  
  341.    You should always free the space in a `regex_t' structure with
  342. `regfree' before using the structure to compile another regular
  343. expression.
  344.  
  345.    When `regcomp' or `regexec' reports an error, you can use the
  346. function `regerror' to turn it into an error message string.
  347.  
  348.  - Function: size_t regerror (int ERRCODE, regex_t *COMPILED, char
  349.           *BUFFER, size_t LENGTH)
  350.      This function produces an error message string for the error code
  351.      ERRCODE, and stores the string in LENGTH bytes of memory starting
  352.      at BUFFER.  For the COMPILED argument, supply the same compiled
  353.      regular expression structure that `regcomp' or `regexec' was
  354.      working with when it got the error.  Alternatively, you can supply
  355.      `NULL' for COMPILED; you will still get a meaningful error
  356.      message, but it might not be as detailed.
  357.  
  358.      If the error message can't fit in LENGTH bytes (including a
  359.      terminating null character), then `regerror' truncates it.  The
  360.      string that `regerror' stores is always null-terminated even if it
  361.      has been truncated.
  362.  
  363.      The return value of `regerror' is the minimum length needed to
  364.      store the entire error message.  If this is less than LENGTH, then
  365.      the error message was not truncated, and you can use it.
  366.      Otherwise, you should call `regerror' again with a larger buffer.
  367.  
  368.      Here is a function which uses `regerror', but always dynamically
  369.      allocates a buffer for the error message:
  370.  
  371.           char *get_regerror (int errcode, regex_t *compiled)
  372.           {
  373.             size_t length = regerror (errcode, compiled, NULL, 0);
  374.             char *buffer = xmalloc (length);
  375.             (void) regerror (errcode, compiled, buffer, length);
  376.             return buffer;
  377.           }
  378.  
  379. 
  380. File: rx.info,  Node: Performance Considerations,  Next: Semantic Tests,  Prev: Posix Entry Points,  Up: Top
  381.  
  382. Performance Considerations
  383. ==========================
  384.  
  385.    In order to use the Rx implementation of Posix regexp functions, you
  386. should include `<rxposix.h>' in your program.
  387.  
  388.    In order to use the Rx implementation of Posix regexp functions most
  389. effectively, it may help to know a bit about performance tuning in Rx.
  390.  
  391. * Menu:
  392.  
  393. * Avoiding Redundant Compilations ::  Compiling Regexps is costly.
  394. * Controlling Memory Use::      You can limit Rx's memory use.
  395.  
  396. 
  397. File: rx.info,  Node: Avoiding Redundant Compilations,  Next: Controlling Memory Use,  Prev: Performance Considerations,  Up: Performance Considerations
  398.  
  399. Avoiding Redundant Compilations
  400. -------------------------------
  401.  
  402.    Rx implements the Posix regexp entry points `regcomp', `regerror',
  403. `regexec', and `regfree'.  Some special considerations apply when using
  404. the Rx versions.
  405.  
  406.    First, `regcomp' is a comparatively expensive operation.
  407. Addiitonally, `regexec' tends to perform better when a compiled
  408. expression is compiled once and used twice than when the pattern is
  409. compiled twice and used twice.  Internally, Rx caches that information
  410. about a pattern which is constructed dynamicly by regexec.  You can save
  411. on compilation costs and maximize the effectiveness of the Rx cache by
  412. re-using compiled expressions when it is convenient.
  413.  
  414.    For example, for reasons unrelated to Rx, it has long been the
  415. practice in GNU emacs to always save one compiled regular expression
  416. (the most recent).  Before compiling a new expression, Emacs checks to
  417. see if the new pattern is the same as the one that is already compiled.
  418. This is the sort of optimization that Rx likes.  (It may even win, in
  419. some cases, to cache more than a single compiled regexp.)
  420.  
  421.    In the long-run, Rx should be modified to cache compilations on its
  422. own.  (*Note Improvements to Make::.)
  423.  
  424.    Sometimes programmers write programs with many regexps, all known
  425. staticly at compile time.  This can be a problem with Rx because when
  426. the program starts up, or as it runs, all of those staticly known
  427. regexps have to be compiled, which may be too time consuming.
  428.  
  429.    One easy fix for programs with many static regexps is to use `flex'
  430. or another lexical-analyzer generator program instead.  Lexer-generators
  431. are optimized for the case of compiling staticly known regexps.
  432.  
  433.    There are still reasons why staticly known regexps may not be
  434. convertable to `flex' input - for example, the Posix pattern language
  435. is more general than `flex''s.  In the long-run, it may be a good idea
  436. to extend Rx to support static compilation of regexps.  (*Note
  437. Improvements to Make::.)
  438.  
  439. 
  440. File: rx.info,  Node: Controlling Memory Use,  Prev: Avoiding Redundant Compilations,  Up: Performance Considerations
  441.  
  442. Controlling Memory Use
  443. ----------------------
  444.  
  445.    The size of the cache used by regexec is subject to control by
  446. programmers.  Additionally, by using lower level entry points,
  447. programmers can create multiple, distinct Rx caches.
  448.  
  449.    This part of the code is subject to change and so is not yet
  450. documented.
  451.  
  452.    See "default_cache" in rxsuper.c and the parameters at the top of
  453. "rxbasic.c" to find some parameters you can tune or hints about creating
  454. alternative regexec caches.
  455.  
  456. 
  457. File: rx.info,  Node: Semantic Tests,  Next: General Functions,  Prev: Performance Considerations,  Up: Top
  458.  
  459. Semantic Tests
  460. ==============
  461.  
  462.    The distribution of *Rx* includes a test-suite, aimed at testing the
  463. conformance of an implementation of the Posix regexp functions to the
  464. standard.
  465.  
  466.    Currently, the tests come from two sources: a test-suite started by
  467. Henry Spencer, and the "Khadafy" test suite by Scott Anderson.
  468.  
  469.    The tests come in three files:
  470.  
  471.    * runtests.c    - The driver program.
  472.  
  473.    * TESTS        - The list of test cases
  474.  
  475.    * TESTS2C.sed    - A script to convert test cases into C.
  476.  
  477. * Menu:
  478.  
  479. * Running the Tests::           Invoking the test suite.
  480. * Adding New Tests::            Extending the test suite.
  481.  
  482. 
  483. File: rx.info,  Node: Running the Tests,  Next: Adding New Tests,  Prev: Semantic Tests,  Up: Semantic Tests
  484.  
  485. Running the Tests
  486. -----------------
  487.  
  488.    To build the test program, use `make runtests'.  (Detailed
  489. configuration and build instructions can be found in INSTALL).
  490.  
  491.    Invoked with no arguments, `runtests' runs all test-cases.  For each
  492. test case, a sequence number is printed.  If there is a problem with
  493. that case, more information is printed.   Output like this:
  494.  
  495.      #0
  496.      #1
  497.      #2
  498.      ...
  499.  
  500.    indicates a successful run.   (The output format is likely to change
  501. in the future to make it easier to automate testing of Rx.)
  502.  
  503.    With a single numeric argument, runtests executes just that test and
  504. no others.  This is handy when debugging.
  505.  
  506.    Sometimes a bug will occur when all tests are run, but disappear when
  507. just the problematic test is run.  Usually this has to do with memory
  508. or cache corruption.
  509.  
  510. 
  511. File: rx.info,  Node: Adding New Tests,  Prev: Running the Tests,  Up: Semantic Tests
  512.  
  513. Adding New Tests
  514. ----------------
  515.  
  516.    This list of tests used by `runtests' is found in the file `TESTS'.
  517. Each line of that file is a list of colon separated fields similar to:
  518.  
  519.      1:^(ab|cd)e:abcde
  520.  
  521.    The first field is the expected return value of regexec, or '2'
  522. meaning that the pattern is not valid.
  523.  
  524.    The second field is the regular expression being tested.
  525.  
  526.    The third field is the string to which the pattern is to be compared.
  527.  
  528.    The file `TESTS2C.sed' is used to convert the test cases into
  529. initializers for an array of structures (which is automated in the
  530. Makefile).
  531.  
  532.    To add a new test case, add lines to `TESTS' and recompile
  533. `runtests'.
  534.  
  535. 
  536. File: rx.info,  Node: General Functions,  Next: Rx Theory,  Prev: Semantic Tests,  Up: Top
  537.  
  538. General Functions
  539. =================
  540.  
  541.    Here is a whirlwind tour of the lower-level Rx entry points and data
  542. structures.  This is not intended to be complete, but rather to be a
  543. help to anyone reading the code itself.
  544.  
  545.    These are presented in the same order in which they might typically
  546. be used.
  547.  
  548. * Menu:
  549.  
  550. * Compiling Expressions::       Strings->Syntax Trees
  551. * Posixly Correct Matches::     Checking for a Posixly correct match.
  552. * Hairy Matches::               Matching with multi-part strings.
  553. * NFA Functions::               Forget Posix, eat NFAs raw.
  554.  
  555. 
  556. File: rx.info,  Node: Compiling Expressions,  Next: Posixly Correct Matches,  Prev: General Functions,  Up: General Functions
  557.  
  558. Compiling Expressions
  559. ---------------------
  560.  
  561.  - Internal Function: reg_errcode_t rx_parse (struct rexp_node **
  562.           rexp_p, __const__ char *pattern, int size, unsigned long
  563.           syntax, int cset_size, unsigned char *translate);
  564.      Compile a regular expression.
  565.  
  566.      REXP_P will return a syntax tree for the pattern.  See
  567.      `"rxnode.h"' to learn about syntax trees.  Minimally, you should
  568.      know that syntax trees are reference counted using `rx_save_rexp'
  569.      and `rx_free_rexp'.
  570.  
  571.      PATTERN and SIZE are the expression and its length.  The
  572.      expression need not be 0-terminated.
  573.  
  574.      The bits set in SYNTAX control details of the language understood
  575.      by the parser.  The meaning of each bit is described in
  576.      `"rxgnucomp.h"'.
  577.  
  578.      CSET_SIZE is usually 256.  It should not be much larger than that
  579.      or space-performance will suffer badly.
  580.  
  581.      TRANSLATE is a translation table - an array of characters.
  582.      Characters in the pattern are looked up in TRANSLATE as they are
  583.      read.  Additionally, the pattern is compiled presuming that the
  584.      same translation table will be applied to characters in the string
  585.      being searched (meaning that the pattern is compiled in such a way
  586.      that the effect will be as if every character in the target string
  587.      is looked up in the translation table, even though the expense of
  588.      that lookup is usually avoided).
  589.  
  590.      A return of 0 indicates success, otherwise, the error can be
  591.      looked up in the `rx_error_msg' array.
  592.  
  593.  - Internal Function: int rx_posix_analyze_rexp (struct rexp_node ***
  594.           subexps, int * n_subexps, struct rexp_node * node, int id)
  595.      Staticly analyze a regular expression in preparation for matching.
  596.  
  597.      This function fills in some fields of the nodes of a syntax tree.
  598.  
  599.      `subexps' and `n_subexps' return a malloced array of pointers into
  600.      the syntax tree, one per parenthesized subexpression.  The caller
  601.      must eventually free this array.
  602.  
  603.      `node' is the pattern to be analyzed.  The tree returned by
  604.      `rx_parse' is suitable for this.
  605.  
  606.      `id' should be 1.
  607.  
  608.      Ignore the return value.
  609.  
  610.      This function is not robust in the case that `malloc' or `realloc'
  611.      returns 0 (which should be fixed).
  612.  
  613.    You might expect that `rx_posix_analyze_rexp' and `rx_parse' should
  614. be combined.  They are not because the actions of
  615. `rx_posix_analyze_rexp' make sense for any syntax tree, regardless of
  616. how it is constructed.  `rx_parse' is just one way to build a syntax
  617. tree - it is subject to replacement and trees can be built without
  618. using a parser at all (c.f. `"rxnode.h"').
  619.  
  620. 
  621. File: rx.info,  Node: Posixly Correct Matches,  Next: Hairy Matches,  Prev: Compiling Expressions,  Up: General Functions
  622.  
  623. Checking for Posixly Correct Matches with One-Piece Strings
  624. -----------------------------------------------------------
  625.  
  626.    Looking for a match that is Posixly correct is conceptually tricky.
  627. Here is one way to think of it:
  628.  
  629.    The Posix expression languages, absent of any consideration of the
  630. meaning of "leftmost-longest", underspecify the return value of
  631. `regexec'.  Consider the example:
  632.  
  633.      Pattern:
  634.          foo\(.*\)\(.*\)bar
  635.      Target string:
  636.          fooxxxbar
  637.  
  638.    Initially it is ambiguous how this should be matched.  The ambiguity
  639. is exposed by considering the possible bindings for the subexpressions
  640. `\1' and `\2':
  641.  
  642.      Possible outcomes:
  643.      
  644.          \1 == "xxx" \2 == ""
  645.          \1 == "xx" \2 == "x"
  646.          \1 == "x" \2 == "xx"
  647.          \1 == "" \2 == "xxx"
  648.  
  649.    Posix tells us that the first outcome is the prefered one if the
  650. illustrated pattern is used alone (this is a consequence of the
  651. "leftmost longest" rule).  But Posix also says the answer may be
  652. different if the pattern is a sub-pattern of a larger pattern.  For
  653. example:
  654.  
  655.      Pattern:
  656.          foo\(.*\)\(.*\)bar\2
  657.      Target string:
  658.          fooxxxbarxx
  659.  
  660.    Now the only acceptable outcome is:
  661.  
  662.          \1 == "x" \2 == "xx"
  663.  
  664.    Three entry points provide a relatively simple interface to this
  665. moderately complicated situation:
  666.  
  667.  - Internal Function: struct rx_solutions * rx_basic_make_solutions
  668.           (struct rx_registers * regs, struct rexp_node * expression,
  669.           struct rexp_node ** subexps, int start, int end, struct
  670.           rx_context_rules * rules, char * str)
  671.  - Internal Function: void rx_basic_free_solutions (struct rx_solutions
  672.           * solns);
  673.  - Internal Function: enum rx_answers rx_next_solution (struct
  674.           rx_solutions * solns)
  675.  - Internal Function: void rx_basic_free_solutions (struct rx_solutions
  676.           * solns)
  677.      `make_solutions' returns a lazilly constructed stream of possible
  678.      solutions for a given regexp and target string.
  679.  
  680.      `next_solution' constructs and returns the next solution from a
  681.      list returned by `make_solutions'.  Solutions are returned in order
  682.      of preferability according to the Posix spec.  So, the first
  683.      solution is the leftmost-longest, and the last, the
  684.      rightmost-shortest.
  685.  
  686.      REGS is where subexpression extents are tracked.
  687.  
  688.      EXPRESSION is the expression to solve.
  689.  
  690.      SUBEXPS is as returned by `rx_posix_analyze_rexp'.
  691.  
  692.      START and END are the integer addresses of the data to be compared
  693.      to the pattern.  A solution must match all characters starting at
  694.      START and ending at `END - 1'.
  695.  
  696.      RULES are some bits that control the precise meaning of "^" and
  697.      "$".  See `"rxcontext.h"'.
  698.  
  699.      STR is the data to be matched.  Note that anchoring operators can
  700.      cause the matcher to look beyond START and END when testing a
  701.      match.  It may make sense to pass START > 0, for example.
  702.  
  703.      `make_solutions' returns a pointer to a solution list, or 0 if an
  704.      allocation fails.
  705.  
  706.      `next_solution' returns a status which can be:
  707.           `rx_yes'    -- The pattern matches exactly.
  708.           `rx_maybe'    -- The pattern does not match, but might
  709.                      if more characters were added to the string.
  710.           `rx_no'    -- The pattern does not match and could not be
  711.                      made to match even by adding more characters.
  712.  
  713.      In addition, REGS is filled in by `next_solution'.
  714.  
  715.      Finally, `free_solutions' is used to release resources consumed by
  716.      a solution list.
  717.  
  718. 
  719. File: rx.info,  Node: Hairy Matches,  Next: NFA Functions,  Prev: Posixly Correct Matches,  Up: General Functions
  720.  
  721. Hairy Matches and Suspendable Searches
  722. --------------------------------------
  723.  
  724.    The functions `rx_basic_make_solutions' and
  725. `rx_basic_free_solutions' are used to find matches in a one-piece
  726. string.  More general entry points are provided for multi-piece strings,
  727. which may or may not be entirely available in memory at one time:
  728.  
  729.  - Internal Function: struct rx_solutions * rx_make_solutions (struct
  730.           rx_registers * regs, struct rx_unfaniverse * verse, struct
  731.           rexp_node * expression, struct rexp_node ** subexps, int
  732.           cset_size, int start, int end, rx_vmfn vmfn, rx_contextfn
  733.           contextfn, void * closure)
  734.  - Internal Function: void rx_free_solutions (struct rx_solutions *
  735.           solns)
  736.      These functions are similar to their `_basic_' analogues, but
  737.      substitute some new parameters for the one piece string:
  738.  
  739.      VMFN is a function provided by the caller that returns at least
  740.      part of the string being matched.
  741.  
  742.      CONTEXTFN is a function provided by the caller that does the work
  743.      of the backreference operators, "^", and "$".
  744.  
  745.      CLOSURE is data provided by the caller, passed through to vmfn and
  746.      contextfn.
  747.  
  748.           typedef enum rx_answers (*rx_vmfn)
  749.                P((void * closure,
  750.               unsigned char ** burst, int * len, int * offset,
  751.               int start, int end, int need));
  752.           
  753.           typedef enum rx_answers (*rx_contextfn)
  754.                P((void * closure,
  755.               int type,
  756.               int start, int end,
  757.               struct rx_registers * regs));
  758.  
  759.      `vmfn' is asked for a range of characters from START to END.  NEED
  760.      is in that range and is the only position that must be returned by
  761.      vmfn.  BURST, LEN, and OFFSET are output parameters.  OFFSET will
  762.      get the integer address of burst, and LEN the number of valid
  763.      characters in the burst.  VMFN may be asked for the empty string
  764.      from END to END and should be able to handle that case.
  765.  
  766.      If `vmfn' provides the needed character, it should return `rx_yes'.
  767.  
  768.      If `vmfn' can't provide the character now, but might be able to
  769.      later, it should return `rx_maybe'.  This will cause
  770.      `rx_next_solution' to quickly return `rx_maybe'.   If
  771.      `rx_next_solution' is called again, it will retry the call to vmfn
  772.      and possibly resume the search.
  773.  
  774.      If `vmfn' can not provide the needed character, it should return
  775.      `rx_no'.  `rx_next_solution' will not normally ask for
  776.      out-of-range characters, so usually there is no good reason to
  777.      return `rx_no', but the code is supposed to be robust in case you
  778.      do.
  779.  
  780.      The `contextfn' also returns a `yes/no/maybe' status.  It tests
  781.      whether the characters in START to END satisfy the operator TYPE.
  782.      `type' is an ascii value; one of the characters in "^$123456789".
  783.  
  784. 
  785. File: rx.info,  Node: NFA Functions,  Prev: Hairy Matches,  Up: General Functions
  786.  
  787. NFA Functions and Super-NFA Functions
  788. -------------------------------------
  789.  
  790.    Not really documented yet.
  791.  
  792.      rx.h, rxnfa.h        -- translating an expression into an NFA.
  793.      
  794.      rxsuper.h        -- optimizing the NFA into a DFA, or at least
  795.                     an NFA with fewer branch points.
  796.      
  797.      rxanal.h        -- how to use DFAs to find longest matches,
  798.                     matches of a specific length, the shortest
  799.                     match, etc.
  800.      
  801.      rxsimp.h        -- Translating a Posix "regular
  802.                     expression" into a true regular expression
  803.                     that describes a superset language.
  804.  
  805. 
  806. File: rx.info,  Node: Rx Theory,  Next: Improvements to Make,  Prev: General Functions,  Up: Top
  807.  
  808. Rx Theory
  809. =========
  810.  
  811.    There are two match algorithms.  One is for truly regular regexps
  812. (those that can be reduced to a dfa).  The other is for non-regular
  813. regexps.
  814.  
  815.    The dfa algorithm implements the idea suggested in `Compilers' by
  816. Aho, Sethi and Ullman:
  817.  
  818.      [One] approach [to pattern matching regular expressions] is to use
  819.      a DFA, but avoid constructing all of the transition table by using
  820.      a technique called "lazy transition evaluation".  Here,
  821.      transitions are computed at run time [when] actually needed.
  822.      [T]ransitions are stored in a cache. [....] If the cache becomes
  823.      full, we can erase some previously computed transition to make
  824.      room for the new transition.
  825.  
  826.    The implementation in Rx is generalized from that, but the above
  827. description covers what is used for Posix patterns.
  828.  
  829.    The non-dfa algorithm implements a "recursive decomposition"
  830. technique described in email by Henry Spencer.  For a given pattern,
  831. this algorithm first checks to see if a simpler, superset language,
  832. DFA-pattern matches.  If it does, then this algorithm does the
  833. detail-work to see if the non-DFA pattern matches.
  834.  
  835.    The detail work usually involves recursing on subpatterns.  For
  836. example, a concatentation of two subexpressions matches a string if the
  837. string can be divided into two parts, each matching one subexpression,
  838. in the right order.  More than one solution is often possible for a
  839. given pattern.  This ambiguity is the subject of the "leftmost longest"
  840. rules in the spec, and the back-tracking oriented stream-of-solution
  841. functions `rx_make_solutions', `rx_next_solution' and
  842. `rx_free_solutions'.
  843.  
  844.      rxspencer.[ch]                 -- The non-DFA algorithm
  845.      rxanal.[ch] rxsuper.[ch] rxnfa.[ch]    -- The DFA algorithm
  846.  
  847. 
  848. File: rx.info,  Node: Improvements to Make,  Prev: Rx Theory,  Up: Top
  849.  
  850. Improvements to Make
  851. ====================
  852.  
  853.    An approximation of the GNU entry points is needed.  This can not
  854. easily be an exact approximation because the GNU entry points have no
  855. function for freeing a compiled expression - they assume that compiled
  856. expressions can be freed using a single call to "free(3)".  For that
  857. reason, do not use the names of the old GNU entry points ...use "rx_"
  858. instead.
  859.  
  860.    This version of Rx hasn't been profiled and tuned.
  861.  
  862.    It might be nice to have some C++ types to hide reference counting
  863. and provide handy constructors for rexp_nodes and nfa parts.
  864.  
  865.    Right now, the regexp->regular regexp mapping in rxsimp.[ch] is
  866. cached for a particular input expression.  I think it would probably be
  867. a big win in many situations if it were cached, like unique nfas (c.f.
  868. rxunfa.[ch]), for equivalent expressions.
  869.  
  870.    It would speed up matching to lift the non-regular constructs to the
  871. top of the syntax tree.   e.g., if you have:
  872.  
  873.      pattern:  "abc$"
  874.      
  875.      syntax tree: (concat (cset "a")
  876.                       (concat (cset "b")
  877.                       (concat (cset "c")
  878.                           (operator "$"))))
  879.  
  880.    it involves a lot more work (in "next_solution) than if you have the
  881. equivalent:
  882.  
  883.      same pattern:  "abc$"
  884.      
  885.      syntax tree: (concat (concat (cset "a")
  886.                       (concat (cset "b")
  887.                           (cset "c")))
  888.                   (operator "$"))
  889.  
  890.    in fact, while doing that, notice that subtrees of nothing-but-concat
  891. can conceivably be optimized so that next_solution just uses "strcmp".
  892.  
  893.    For that matter, a tree which is a disjunction of conjunction (a
  894. tree of "|" whose leaves are trees of concat nodes) could be optimized
  895. to use a table method (Boyer/Moore?).  Again, this would be for
  896. next_solution but might involve adding stuff to rx_posix_analyze_rexp.
  897.  
  898.    As more and more optimizations are added, programmers should be given
  899. simple control over which optimizations are important for a particular
  900. pattern.  For example, packages in emacs often include a few regexps
  901. that are used heavily - it would be worth the trouble to arrange for
  902. those regexps to be compiled specially.
  903.  
  904.    Static compilation of regexps is mostly a job for lex, but posix
  905. patterns are more general and have a nicer interface.  What's more, it'd
  906. be nice to have the benefits of static compilation even for dynamicly
  907. loaded regexps (e.g., imagine if when an emacs lisp file is
  908. byte-compiled, the regexps it contains are also compiled).
  909.  
  910.    A lot of optimizations apply to just syntax trees.  One approach to
  911. static compilation is to make an ugly but fast-reading syntax for trees,
  912. and a printer for that syntax.  Then, after optimiztaions, a pattern
  913. could be stored as a string and later read back in, already optimized.
  914.  
  915.    A similar trick could be done for the nfa built in rxnfa.c.
  916.  
  917.    next_solution already considers the length of a fixed-length
  918. subexpression, but many more lenght optimizations are possible.  I'd
  919. guess these will pay off well.
  920.  
  921.  
  922. 
  923. Tag Table:
  924. Node: Top83
  925. Node: Posix Entry Points638
  926. Node: POSIX Regexp Compilation1546
  927. Node: Flags for POSIX Regexps5626
  928. Node: Matching POSIX Regexps6530
  929. Node: Regexp Subexpressions8688
  930. Node: Subexpression Complications10740
  931. Node: Regexp Cleanup13096
  932. Node: Performance Considerations15419
  933. Node: Avoiding Redundant Compilations15989
  934. Node: Controlling Memory Use18120
  935. Node: Semantic Tests18719
  936. Node: Running the Tests19445
  937. Node: Adding New Tests20369
  938. Node: General Functions21121
  939. Node: Compiling Expressions21775
  940. Node: Posixly Correct Matches24531
  941. Node: Hairy Matches28136
  942. Node: NFA Functions31078
  943. Node: Rx Theory31742
  944. Node: Improvements to Make33591
  945. 
  946. End Tag Table
  947.